//
//  BusinessSearchController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/10/25.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "BusinessSearchController.h"
#import "SearchHistoryView.h"

#import "BusinessViewCell.h"
#import "BusinessDetailsController.h"
#import "BusinessModel.h"

#import "LogInViewController.h"

@interface BusinessSearchController ()<UISearchBarDelegate,SearchHistoryViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    NSString *_filename;
    MBProgressHUD *progressHUD;
    NSUInteger refreshIndex;
    UIImageView *noDrawImage;
    
    //搜索或者选中商品名字
    NSString *_selectStr;
}
@property (nonatomic,strong)UISearchBar *searchBar;
/**
 *  历史记录
 */
@property(nonatomic,strong)NSMutableArray *histArray;

@property(nonatomic,strong)SearchHistoryView *HistoryView;

@property(nonatomic,strong)NSFileManager *filePath;

@property(nonatomic,strong)UITableView *searchView;
/**
 *  数据数组
 */
@property(nonatomic,strong)NSMutableArray *searchArray;

@end

@implementation BusinessSearchController

static NSString *const businessSearchIdentifier = @"businessSearchIdentifier";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self buildView];
    [self businessHistoryList];
    
    refreshIndex = 1;
}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    [_searchBar resignFirstResponder];
}

#pragma mark SearchBar代理
//已经结束编辑的回调
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    
}

//搜索按钮点击的回调
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"%@",searchBar.text);
    
    _selectStr = searchBar.text;
    //搜索请求
    [self bussinessSearchListDataSearchStr:_selectStr];
  
    [self.histArray addObject:searchBar.text];
    //将记录存入本地
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
    _filename = [path stringByAppendingPathComponent:@"HistoryList.plist"];
    _filePath = [NSFileManager defaultManager];
    [_filePath createFileAtPath:_filename contents:nil attributes:nil];
    
    BOOL stutas = [self.histArray writeToFile:_filename atomically:YES];
    if (stutas) {
        NSLog(@"成功");
    } else {
        NSLog(@"失败");
    }
    _HistoryView.historyArray = self.histArray;
    
}

#pragma mark 历史记录
- (void)businessHistoryList
{
    self.HistoryView = [[SearchHistoryView alloc] initWithFrame:CGRectMake(0,0, WIDTH,100 )];
    _HistoryView.delegate = self;
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
    NSLog(@"%@",path);
    
    _filename = [path stringByAppendingPathComponent:@"HistoryList.plist"];
    self.histArray = [NSMutableArray arrayWithContentsOfFile:_filename];

    _HistoryView.historyArray = self.histArray;
    [self.view addSubview:_HistoryView];
}

//点击
- (void)SearchHistoryDelegateClick:(NSInteger)selectIndex
{
    _selectStr = self.histArray[selectIndex];
    NSLog(@"selectStr%@",_selectStr);
    _searchBar.text = _selectStr;
    //搜索请求
    [self bussinessSearchListDataSearchStr:_selectStr];
}

//删除
- (void)SearchHistorydeleteClick
{
    
    //弹框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定删除全部历史记录?" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okay = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //数组接受本地删除
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
        _filename = [path stringByAppendingPathComponent:@"HistoryList.plist"];
        self.histArray = [NSMutableArray arrayWithContentsOfFile:_filename];

        [self.histArray removeAllObjects];
//         NSLog(@"???%@",self.histArray);
        
        _HistoryView.isDelete_History = YES;
        _HistoryView.historyArray = self.histArray;
        //删除本地
        NSFileManager *manager=[NSFileManager defaultManager];
        NSString *filepath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"HistoryList.plist"];
        
        NSLog(@"%@",filepath);
        
        if ([manager removeItemAtPath:filepath error:nil]) {
            NSLog(@"文件删除成功");
        }
        
        
    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    
    [alert addAction:okay];
    [alert addAction:cancle];
    
    [self presentViewController:alert animated:YES completion:nil];
 
}

#pragma mark 上拉刷新
#pragma mark >>>>>>>>刷新
- (void)addPullUpdateData
{
    self.searchView.mj_footer = [TopPullRefreshAnaimation footerWithRefreshingTarget:self refreshingAction:@selector(bussinessSearchListMoreData)];
    
}

- (void)bussinessSearchListMoreData
{
    refreshIndex ++;
    [self bussinessSearchListDataSearchStr:_selectStr];
    [self.searchView.mj_footer endRefreshing];
}


#pragma mark 商家搜索请求
- (void)bussinessSearchListDataSearchStr:(NSString *)searchStr
{
    //菊花加载
    progressHUD = [MBProgressHUD loadingInformationToView];
    [self.view addSubview:progressHUD];
    
    [self.searchBar resignFirstResponder];
    
    if (refreshIndex == 1) {
        [self.searchArray removeAllObjects];
    }
    
    
    if (self.searchView == nil) {
        [self buildTableView];
    }
    
    NSString *P = [NSString stringWithFormat:@"%ld",refreshIndex];
    
    NSDictionary *params = @{
                             @"search_text":searchStr,
                             @"p":P
                             };
    NSLog(@"%@",params);
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Business/searchShop" completeBlock:^(id object) {
        
        NSLog(@"--------%@",object);
        NSArray *arr = object[@"data"];
        if (JudgeBackDataCode) {
            
            for (NSDictionary *dict in arr) {
                BusinessModel *businessModel = [[BusinessModel alloc] initWithDictionary:dict error:nil];
                if (businessModel) {
//                    NSLog(@"%@",businessModel);
                    [self.searchArray addObject:businessModel];
                }
            }
            
            if (self.searchView == nil) {
                [self buildTableView];
            }
            
            
        }else{
        
            refreshIndex = 1;
            [self.searchView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.searchView reloadData];
        [progressHUD hide:YES];
        [progressHUD removeFromSuperViewOnHide];
    }];
    
    
}

#pragma mark 数据源代理
#pragma mark>>>>>>>>>>>数据源
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    BusinessViewCell *cell = [tableView dequeueReusableCellWithIdentifier:businessSearchIdentifier];
    
    if (cell==nil) {
        
        cell = [[BusinessViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:businessSearchIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    BusinessModel *businessModel = self.searchArray[indexPath.row];
    [cell.shopsImg sd_setImageWithURL:[NSURL URLWithString:businessModel.sdpic] placeholderImage:[UIImage imageNamed:@"businessNopict.jpg"]];
    cell.shopsNameLabel.text = businessModel.title;
    cell.shopsDetailsLabel.text = businessModel.zycp;
    [cell.shopsAddress setTitle:businessModel.county forState:UIControlStateNormal];
    
    cell.messageButton.tag = indexPath.row;
    [cell.messageButton addTarget:self action:@selector(touchUpInSideMessageButton:) forControlEvents:UIControlEventTouchUpInside];
    if (JudgeInvididualOrSeller) {
        cell.messageButton.hidden = NO;
    } else {
        cell.messageButton.hidden = YES;
    }
    
    return cell;
}

- (void)touchUpInSideMessageButton:(UIButton *)button {
    
    NSLog(@"%@",self.searchArray[button.tag]);
    
    if ([JudgeUserLogInTool JudgeUserLonInStatus:self.view]) {
        BusinessModel *model = self.searchArray[button.tag];
        
        ChatViewController *chat = [[ChatViewController alloc] initWithConversationChatter:model.username conversationType:EMConversationTypeChat];
        chat.FromSellerNumber = model.username;
        chat.title = model.title;
        [self.navigationController pushForm:self.navigationController pushToAndHidden:chat];
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您尚未登录用户" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LogInViewController *accountVC = [[LogInViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:accountVC];
            [self presentViewController:nav animated:YES completion:nil];
        }];
        [alert addAction:SettingAction];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

#pragma mark>>>>>>>>>>>>代理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BusinessDetailsController *detailVC = [[BusinessDetailsController alloc] init];
    BusinessModel *businessModel = self.searchArray[indexPath.row];
    detailVC.bussinessId = businessModel.replaceID;
    [self.navigationController pushForm:self.navigationController pushToAndHidden:detailVC];
}



# pragma  mark  UI
- (void)buildTableView
{
    [noDrawImage removeFromSuperview];
    [_HistoryView removeFromSuperview];
    
    if (self.searchArray.count == 0) {
        //暂无地址(图)
        noDrawImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"noSearchBussiness"]];
        [self.view addSubview:noDrawImage];

        [noDrawImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX);
            make.centerY.equalTo(self.view.mas_centerY).offset(-HEIGHT/5);
            make.width.mas_equalTo(WIDTH/2);
            make.height.mas_equalTo(HEIGHT/4);
        }];
    }else{
        
        UITableView *searchView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStylePlain];
        self.searchView = searchView;
        [self.view addSubview:searchView];
        self.searchView.rowHeight = HEIGHT/5;
        searchView.backgroundColor = [UIColor whiteColor];
        searchView.delegate = self;
        searchView.dataSource = self;
        
        [self addPullUpdateData];
    }

    
}


- (void)buildView
{
    CGRect frame;
    if (WIDTH == 320) {
        frame = CGRectMake(-25, 0, 200, 30);
    } else {
        frame = CGRectMake(0, 0, 200, 30);
    }
 
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0,WIDTH * 0.7, 30)];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.masksToBounds = YES;
    view.layer.cornerRadius = 6;
    view.layer.borderColor = [UIColor colorWithRed:100 / 255.0 green:100 / 255.0 blue:100 / 255.0 alpha:1].CGColor;
    view.layer.borderWidth = 0.2;
    
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:frame];
    _searchBar.placeholder = @"在此输入商家名称";
    _searchBar.barTintColor = [UIColor whiteColor];
    _searchBar.keyboardType = UIKeyboardAppearanceDefault;
    _searchBar.delegate = self;
    [_searchBar becomeFirstResponder];
    self.navigationItem.titleView = _searchBar;
}

- (NSMutableArray *)histArray
{
    if (!_histArray) {
        _histArray = [[NSMutableArray alloc] init];
    }
    return _histArray;
}

- (NSMutableArray *)searchArray
{
    if (!_searchArray) {
        _searchArray = [[NSMutableArray alloc] init];
    }
    return _searchArray;
}

@end
